#!/bin/sh

#Copyright (c) 2014 Luigi Tarenga <luigi.tarenga@gmail.com>
#Distributed under the terms of a MIT license.

# parameters: [ lock_name [ timeout [ timeout2 ] ] ]

export LANG=C

cd ${0%/*}

lname=${1:-default}
timeout=${2:-30}
timeout2=${3:-0}

read lock_servers < conf/lock_servers
read rpath        < conf/remote_path
read sshopt       < conf/sshopt
read holder term value previous < temp/${lname}_htvp
IFS=: read hostname majority control_master < temp/${lname}_params

log () { [ -n "$verbose" ] && echo $@ >&2 ; }

#
# if holder send release request
#
if [ "$holder" = "$hostname" ] ; then
   value=$((value+1))
   release=true
   for h in $lock_servers ; do
      ssh $sshopt $h cd $rpath \; internals/increase-value $hostname $lname $term $value $release \
         > temp/${h}_${lname}_output < /dev/null &
   done

   wait
fi

echo $((timeout+timeout2))  > temp/${lname}_counter
echo "-invalid-" 0 0 "-invalid-" > temp/${lname}_htv
log good. lock released
